package cn.lut.controller;

import cn.lut.entity.Student;
import cn.lut.service.StudentService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @user:dell
 * @date:2020年11月03 09:04
 */
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       req.setCharacterEncoding("utf-8");
       resp.setContentType("text/html; charset=utf-8");
        String id = req.getParameter("id");
        String name = req.getParameter("name");
        String email = req.getParameter("email");
        String age = req.getParameter("age");

//        String config= "spring.xml";
//        ApplicationContext applicationContext=new ClassPathXmlApplicationContext(config);
//
//        使用框架中的方法，获取容器对象
        WebApplicationContext applicationContext=null;
        ServletContext servletContext = getServletContext();
     applicationContext  = WebApplicationContextUtils.getWebApplicationContext(servletContext);


        StudentService studentService = (StudentService) applicationContext.getBean("studentService");
        Student student=new Student();
        student.setId(Integer.parseInt(id));
        student.setName(name);
        student.setEmail(email);
        student.setAge(Integer.parseInt(age));
        studentService.addStudent(student);
        req.getRequestDispatcher("/result.jsp").forward(req,resp);
    }
}
